import { ref, onMounted, reactive } from "vue";
import type { PaginationProps, LoadingConfig } from "@pureadmin/table";
import {
  type wikiDTO,
  getWikiList,
  deleteWiki,
  getWikiById,
  updateWikiTopOrPublish
} from "@/api/blog/wiki";
import { message } from "@/utils/message";

export function useColumns() {
  const widiDialog = ref(Date.now());
  const param = reactive({
    currentPage: 1,
    pageSize: 10,
    title: null,
    isTop: null,
    isPublish: null
  });
  const wikiForm = reactive<wikiDTO>({
    id: undefined,
    title: "",
    summary: "", // 知识库摘要
    cover: "", //知识库封面
    coverList: []
  });
  const primaryParam = reactive({ ...param });
  const tableImageList = ref([]);
  const tableData = ref([]);
  const categoryOptionList = ref([]);
  const tagOptionList = ref([]);
  const loading = ref(false);
  const tableSize = ref("small");
  const selectList = ref<any>([]);
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left",
      width: 40
    },
    {
      label: "序号",
      type: "index",
      width: 55
    },
    {
      label: "标题",
      prop: "title",
      minWidth: 130
    },

    {
      label: "封面",
      prop: "cover",
      width: 200,
      slot: "image"
    },
    {
      label: "知识库描述",
      prop: "summary",
      minWidth: 130
    },
    {
      label: "是否置顶",
      prop: "isTop",
      slot: "isTop"
    },
    {
      label: "是否发布",
      prop: "isPublish",
      slot: "isPublish"
    },
    {
      label: "发布日期",
      prop: "createTime"
    },
    {
      label: "修改日期",
      prop: "updateTime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "right",
    background: true
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });
  // tabChange
  const tabChange = (val: any) => {
    param.isPublish = val.index != 0 ? Number(val.index) : null;
    pageGetWikiList();
  };
  // 搜
  function onSearch() {
    pageGetWikiList();
  }

  // 重置参数
  const resetParam = () => {
    Object.assign(param, primaryParam);
    pageGetWikiList();
  };

  // 修改知识库置顶信息
  async function changeTopOrPublish(val, type) {
    if (val) {
      const { id, isTop, isPublish } = val;
      const res = await updateWikiTopOrPublish(
        id,
        type,
        type === 0 ? isTop : isPublish
      );
      const msg = type == 0 ? "置顶" : "发布";
      if (res) {
        message(
          `${(type === 0 ? isTop : isPublish) == 1 ? msg : "取消" + msg} 成功`,
          {
            type: "success"
          }
        );
      }
    }
  }

  function onSizeChange(val) {
    param.pageSize = val;
    pageGetWikiList();
  }

  function onCurrentChange(val) {
    if (typeof val == "number") {
      loadingConfig.text = `正在加载第${val}页...`;
      param.currentPage = val;
      pageGetWikiList();
    }
  }
  const dialogVisible = ref(false);
  const dialogTitle = ref("新增知识库");

  async function openWikiDialog(row = null) {
    dialogTitle.value = row?.id ? "编辑知识库" : "新增知识库";
    if (row?.id) {
      const res = await getWikiById(row.id);
      if (res) {
        const { cover } = res;
        Object.assign(wikiForm, res);
        wikiForm.id = row.id;
        wikiForm.coverList = [
          {
            // 获取数组最后一位有很多种方法 article_cover.split('/').reverse()[0]
            //           article_cover.split('/').slice(-1)
            //           article_cover.split('/').at(-1)
            id: 1,
            name: cover.split("/").pop(),
            url: cover
          }
        ];
        dialogVisible.value = true;
      }
    } else {
      Object.assign(wikiForm, {
        id: undefined,
        title: "",
        summary: "", // 知识库摘要
        cover: "", //知识库封面
        coverList: []
      });
      dialogVisible.value = true;
    }
  }
  // 知识库目录
  const documentVisible = ref(false);
  const wikiId = ref<number>(1);
  async function openDocumentDialog(row) {
    wikiId.value = row.id;
    documentVisible.value = true;
  }
  function handleSuccess() {
    dialogVisible.value = false;
    onSearch();
  }

  async function deleteBatch() {
    if (selectList.value.length) {
      const list = selectList.value.map(se => se.id);
      const res = await deleteWiki(list);
      if (res) {
        message(`批量删除知识库成功`, { type: "success" });
        pageGetWikiList();
      }
    } else {
      message("请先选择知识库", { type: "warning" });
    }
  }
  function handleSelectionChange(val) {
    selectList.value = val;
  }

  // 分页获取知识库
  async function pageGetWikiList() {
    loading.value = true;
    const res = await getWikiList(param);

    if (res) {
      tableData.value = res.list;
      pagination.total = res.total;
      tableImageList.value = [];
      tableImageList.value = tableData.value.map(v => {
        return v.cover;
      });
    }
    loading.value = false;
  }

  onMounted(async () => {
    // 获取知识库列表
    await pageGetWikiList();
  });

  return {
    param,
    loading,
    columns,
    tableData,
    tableImageList,
    tableSize,
    pagination,
    loadingConfig,
    tagOptionList,
    categoryOptionList,
    tabChange,
    resetParam,
    onSearch,
    onSizeChange,
    onCurrentChange,
    wikiForm,
    dialogTitle,
    widiDialog,
    wikiId,
    openWikiDialog,
    openDocumentDialog,
    documentVisible,
    handleSuccess,
    dialogVisible,
    changeTopOrPublish,
    handleSelectionChange,
    deleteBatch
  };
}
